package fruit

import (
	"fruit/actor/gate"
	"fruit/actor/iactor"
	"fruit/actor/logic"
	"fruit/lib"
	"fruit/tools/proto/proto_out/base"
	"sync"

	"google.golang.org/protobuf/proto"
)

type FruitActor struct {
	*iactor.Actor
}

var once sync.Once
var fruit_actor *FruitActor

func GetFruitActor() *FruitActor {
	once.Do(func() {
		fruit_actor = new(FruitActor)
		// fruit_actor.init()
	})
	return fruit_actor
}

func (my *FruitActor) InitIActor(...interface{}) interface{} {
	// uid := "" //strconv.FormatInt(lib.Index("fruit"), 10)
	// my.Actor = iactor.NewActor(uid, "fruit_actor_"+uid)
	return nil
}

func (my *FruitActor) Create(str []byte) proto.Message {
	req_msg := &base.CreateReq{}
	proto.Unmarshal(str, req_msg)
	var iact iactor.IActor
	// act := iactor.NewActor()
	resp := &base.CreateResp{}
	switch req_msg.Type {
	case "gate":
		iact = gate.GetGateServer()
	case "gate.gateuser":
		iact = gate.CreateGateUser()
	case "logic":
		iact = logic.GetLogicServer()
	}
	if iact != nil {
		resp_inf := lib.RegisterActor(req_msg.Type, iact, req_msg.Data)
		resp.Uid = iactor.Uid(iact)
		if resp_inf != nil {
			resp_proto := resp_inf.(proto.Message)
			data, _ := proto.Marshal(resp_proto)
			resp.Data = data
		}
		return resp
	}

	return nil
}

func (my *FruitActor) Destory(str []byte) proto.Message {
	req_msg := &base.DestoryReq{}
	proto.Unmarshal(str, req_msg)
	lib.UnregisterActor(req_msg.Uid)
	return nil
}

func (my *FruitActor) Ping([]byte) proto.Message {
	return nil
}

func (my *FruitActor) WakeUp(str []byte) proto.Message {
	req_msg := &base.WakeUpReq{}
	proto.Unmarshal(str, req_msg)
	lib.WakeUp(req_msg.EventId, req_msg.From, req_msg.Data)
	return nil
}
